package com.example.plugin.util;

import android.webkit.WebView;
import com.example.plugin.APP;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 网络访问类
 */
public class HttpRequest {
    private static ExecutorService threadPool=Executors.newSingleThreadExecutor();
    private static String useragent = new WebView(APP.context).getSettings().getUserAgentString();
    public static String get(String url){
        return get(url,null,null);
    }
    public static String get(String url,String cookies){
        return get(url,cookies,null);
    }
    //异步
    public static String get(String url,String cookies,HashMap<String,String> requestMap){
        if(url==null || url.equalsIgnoreCase(""))
            return "";
        BufferedReader reader=null;
        try{
            URL url1=new URL(url);
            URLConnection conn=url1.openConnection();
            conn.setRequestProperty("Accept","*/*");
            conn.setRequestProperty("Referer",url);
            conn.setRequestProperty("Accept-Language","zh");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection","keep-Alive");
            conn.setRequestProperty("User-Agent",useragent);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            if(cookies!=null)
                conn.setRequestProperty("Cookie",cookies);
            if(requestMap!=null){
                Iterator iterator=requestMap.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String,String> entry=(Map.Entry<String, String>) iterator.next();
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            conn.connect();
            reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb=new StringBuffer();
            int temp=-1;
            while((temp=reader.read())!=-1){
                sb.append((char)temp);
            }
            return sb.toString();
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }finally {
            if(reader!=null){
                try{
                    reader.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static String post(String url){
        return post(url,null,null,null,null);
    }
    public static String post(String url,String param){
        return post(url,param,null,null,null);
    }
    //同步
    public static String getSync(final String url){
        class C implements Callable<String> {
            @Override
            public String call() {
                try{
                    return get(url,null,null);
                }catch (Exception e){
                    e.printStackTrace();
                    return "";
                }
            }
        }
        Future<String> future=threadPool.submit(new C());
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }
    //同步
    public static String postSync(final String url,final String param,final String cookies){
        class C implements Callable<String> {
                @Override
                public String call() {
                    try{
                        return post(url,param,cookies,null,null);
                    }catch (Exception e){
                        e.printStackTrace();
                        return "";
                    }
                }
        }
        Future<String> future=threadPool.submit(new C());
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    public static String post(String url,String param,String cookies){
        return post(url,param,cookies,null,null);
    }
    public static String post(String url,String param,String cookies,HashMap<String,String> requestMap){
        return post(url,param,cookies,requestMap,null);
    }
    //异步
    public static String post(String url,String param,String cookies,HashMap<String,String> requestMap,byte[] bytes){
        if(url==null || url.equals(""))
            return "";
        BufferedReader reader=null;
        try{
            URL url1=new URL(url);
            URLConnection conn=url1.openConnection();
            conn.setRequestProperty("Accept","*/*");
            conn.setRequestProperty("Referer",url);
            conn.setRequestProperty("Accept-Language","zh");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection","keep-Alive");
            conn.setRequestProperty("User-Agent",useragent);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            if(cookies!=null)
                conn.setRequestProperty("Cookie",cookies);
            if(requestMap!=null){
                Iterator iterator=requestMap.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String,String> entry=(Map.Entry<String, String>) iterator.next();
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            PrintWriter out=new PrintWriter(conn.getOutputStream());

            if(param!=null){
                out.print(param);
                out.flush();
            }
            if(bytes!=null){
                DataOutputStream dataOut=new DataOutputStream(conn.getOutputStream());
                //每次发送1024字节，防止一次性发送给软件增加负载
                if(bytes.length>=1024){
                    int n=bytes.length/1024;
                    int r=bytes.length%1024;
                    if(r>0) n++;
                    for(int i=0;i<n;i++){
                        if(i==n-1){
                            dataOut.write(bytes,1024*i,r);
                        }else{
                            dataOut.write(bytes,1024*i,1024);
                        }
                    }
                }else{
                    dataOut.write(bytes,0,bytes.length);
                }
                dataOut.flush();
            }
            reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb=new StringBuffer();
            int temp=-1;
            while((temp=reader.read())!=-1){
                sb.append((char)temp);
            }
            return sb.toString();
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }finally {
            if(reader!=null){
                try{
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }


}
